

import 'package:get/get.dart';
import 'package:rc_widget/rc_widget.dart';

import 'app_getx_controller.dart';
export 'app_getx_controller.dart' show LoadingStatus;

enum HttpMethod {
  get,
  post,
}

abstract class AppGetxListController<T> extends AppGetxController {
  /// 页码
  int page = 1;

  /// 列表数据
  RxList<T> list = RxList<T>();

  /// 是否加载中
  bool loading = false;

  /// 是否最后一页
  bool isLastPage = false;

  /// 日志输出
  bool get isPrint => false;

  /// 是否初始化请求
  bool get immediate => true;

  /// 请求方式
  HttpMethod get httpMethod => HttpMethod.get;

  /// 参数扩展
  Map<String, dynamic> get extendedParams => {};

  /// 请求地址
  String get url;

  /// json格式化
  JsonData<T> fromJson(Map<String, dynamic> json);

  @override
  void onInit() {
    super.onInit();

    if (immediate) getList();
  }

  /// 下拉刷新
  Future<void> onRefresh() => getList();

  /// 上拉加载
  Future<void> onLoad() => getList(false);

  /// 重新加载数据
  Future<void> reload({bool showLoading = true}) async {
    if (showLoading) {
      changeLoadingStatus(LoadingStatus.loading);
      await Future.delayed(const Duration(milliseconds: 300));
    }

    await getList();
  }

  /// 获取列表数据
  Future<void> getList([bool isRefresh = true]) async {
    if (isRefresh) {
      page = 1;
      isLastPage = false;
    }

    if (loading || isLastPage) return;

    loading = true;

    final Map<String, dynamic> params = {
      'page': page,
      'size': 10,
      ...extendedParams,
    };

    late final JsonData<T> result;

    if (httpMethod == HttpMethod.get) {
      result = await RcHttp.get<JsonData<T>>(
        url,
        params: params,
        isPrint: isPrint,
        cancelToken: cancelToken,
        errorJson: () => JsonData.error(),
        fromJson: (json) => fromJson(json),
      );
    } else {
      result = await RcHttp.post(
        url,
        data: params,
        isPrint: isPrint,
        cancelToken: cancelToken,
        errorJson: () => JsonData.error(),
        fromJson: (json) => fromJson(json),
      );
    }

    if (result.code == 200) {
      if (isRefresh) {
        list.value = result.list;
      } else {
        list.addAll(result.list);
      }

      page++;
      isLastPage = result.isLastPage;

      changeLoadingStatus(LoadingStatus.success);
    } else {
      changeLoadingStatus(LoadingStatus.error);
    }

    loading = false;
  }
}

class JsonData<T> {
  JsonData({
    required this.code,
    required this.list,
    required this.isLastPage,
  });

  /// 状态码
  final int code;

  /// 列表数据
  final List<T> list;

  /// 是否最后
  final bool isLastPage;

  factory JsonData.error() => JsonData(
        code: 400,
        list: [],
        isLastPage: true,
      );
}
